const setStatus = require("../common/setStatus");
const { invoke, query } = require('../tools/index.js');

const SELLER = ("seller").toUpperCase();

const queryOptions = {
    username: "seller33",
    chaincodeId: "seller",
    fcn: null,
    args: [],
    host: '120.79.19.57',
    org: '3'
}

const invokeOptions = {
    host: "120.79.19.57",
    orderHost:"139.199.191.238",
    org:"3",
    username: "seller33",
    chaincodeId: "seller",
    channelId: "mychannel",
    fcn: null,
    args: [],
}

function setQuery(fcn, args) {
    return Object.assign(queryOptions, {fcn, args});
}

function setInvoke(fcn, args) {
    return Object.assign(invokeOptions, {fcn, args});
}

module.exports = {
    getQuery:async (ctx) => {
        const {QueryId} = ctx.request.query;
        if (!QueryId) {
            setStatus(ctx, 200,0,"","无请求参数id");
            return;
        }
        const data = await query(setQuery("query", [QueryId]));
        setStatus(ctx, 200,1,data);
    },
    // seller
    getSeller: async (ctx) => {
        const {SellerId} = ctx.request.query;
        if (!SellerId) {
            setStatus(ctx, 200,0,"","无请求参数id");
            return;
        }
        const data = await query(setQuery("query", [ SellerId]));
        setStatus(ctx, 200,1,data);
    },
    getSellerAll:async (ctx) => {
        const data = await query(setQuery("queryAll", [""]));
        setStatus(ctx, 200,1,data);
    },
    createSeller:  async (ctx) => {
        const {Name ,Address} = ctx.request.body;
        if (!Name || !Address) {
            setStatus(ctx, 200,0,"","缺少参数");
            return;
        }
        const SellerId = SELLER + new Date().getTime();
        const args = [SellerId, Name, Address];
        await invoke(setInvoke("create", [ ...args]));
        setStatus(ctx, 200,1,"");
    },
    changeSeller: async (ctx) => {
        const {SellerId, Name ,Address} = ctx.request.body;
        if(!SellerId||!Name||!Address) {
            setStatus(ctx, 200,0,"","缺少参数");
            return;
        }
        const args = [SellerId, Name, Address];
        await invoke(setInvoke("change", [...args]));
        setStatus(ctx, 200,1,"");
    },
    delSeller: async (ctx) => {
        const {SellerId} = ctx.request.body;
        if(!SellerId) {
            setStatus(ctx, 200,0,"","缺少参数");
            return;
        }
        await invoke(setInvoke("delete", [SellerId]));
        setStatus(ctx, 200,1,"");
    },

};